package cn.lysj.framework.common.validate.reflect;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author ww
 * @date 2018-08-20 9:17
 * @Description 说明
 */
public class ClassUtil {

    /**
     * explain:获取当前线程中的ClassLoader类加载器
     * @return
     */
    public static ClassLoader getClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * explain: 判断字符串是否为null、""、" "
     * @param arg 待判断的字符串
     **/
    public static boolean isBlank(String arg) {
        return null == arg || ("".equals(arg.replace(" ", "")));
    }

    /**
     * explain:加载类
     * @param className 注解的路径
     * @param isInitialized 是否进行初始化
     * @return
     */
    public static Class<?> loadClass(String className, boolean isInitialized) {
        Class<?> clazz;
        try {
            clazz = Class.forName(className, isInitialized, getClassLoader()); //获取所有的注解类路径  interface org.yxs.medusa.annotation.Email
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("load class failure", e);
        }
        return clazz;
    }

    /**
     * explain:加载类并放入classSet
     * @param classSet 用于存放加载类
     * @param className 注解的路径
     */
    private static void doAddClass(Set<Class<?>> classSet, String className) {
        Class<?> clazz = loadClass(className, false); //interface org.yxs.medusa.annotation.Email
        classSet.add(clazz);
    }

    /**
     * explain: 将基础包下的所有class放入classSet
     * @param classSet 用于存放加载类
     * @param packagePath 注解包的绝对路径
     * @param packageName 注解包的路径
     */
    private static void addClass(Set<Class<?>> classSet, String packagePath, String packageName) {
        File[] files = new File(packagePath).listFiles(new FileFilter() {
            public boolean accept(File file) {
                return (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory();
            }
        });
        //file = C:\Users\Administrator\Desktop\medusa-master\target\classes\org\yxs\medusa\annotation\Email.class
        for(File file : files) {
            String fileName = file.getName();//Email.class
            if(file.isFile()) {
                String className = fileName.substring(0, fileName.lastIndexOf("."));
                if(!isBlank(packageName)) {
                    className = packageName + "." + className; //获取所有的注解类路径  org.yxs.medusa.annotation.Email
                }
                doAddClass(classSet, className);
            } else {
                String subPackagePath = fileName;
                if(!isBlank(packagePath)) {
                    subPackagePath = packagePath + "/" + subPackagePath;
                }
                String subPackageName = fileName;
                if(!isBlank(packageName)) {
                    subPackageName = packageName + "." + subPackageName;
                }
                addClass(classSet, subPackagePath, subPackageName);
            }
        }
    }


    /**
     * 获取基础包下的所有类
     * @param packageName 注解包的路径
     * @return
     */
    public static Set<Class<?>> getClassSet(String packageName) {
        Set<Class<?>> classSet = new LinkedHashSet<Class<?>>();

        try {
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
            while(urls.hasMoreElements()) {
                URL url = urls.nextElement();
                if(null != url) {
                    String protocol = url.getProtocol(); //file
                    if("file".equals(protocol)) {
                        // url.getPath() == C:/Users/Administrator/Desktop/medusa-master/target/classes/org/yxs/medusa/annotation
                        String packagePath = url.getPath().replaceAll("20%", ""); //org.yxs.medusa.annotation
                        addClass(classSet, packagePath, packageName);

                    }else if("jar".equals(protocol)) {
                        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                        if(null != jarURLConnection) {
                            JarFile jarFile = jarURLConnection.getJarFile();
                            if(null != jarFile) {
                                Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
                                while(jarEntryEnumeration.hasMoreElements()) {
                                    JarEntry jarEntry = jarEntryEnumeration.nextElement();
                                    String jarEntryName = jarEntry.getName();
                                    if(jarEntryName.endsWith(".class")) {
                                        String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/",".");
                                        doAddClass(classSet, className);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("get class set failure", e);
        }
        return classSet;
    }

}
